// 认证控制器
import authService from '../services/authService.js';

/**
 * 用户注册控制器
 * 处理用户注册请求
 * @param {Object} request - Fastify请求对象，包含用户名、邮箱和密码
 * @param {Object} reply - Fastify响应对象
 * @returns {Object} 注册结果响应
 */
async function register(request, reply) {
  try {
    const { username, email, password } = request.body;
    const result = await authService.registerUser(username, email, password);
    return reply.code(201).send({
      code: 1,
      success: true,
      message: '注册成功',
      data: result
    });
  } catch (error) {
    return reply.code(400).send({
      code: 10001,
      success: false,
      message: error.message,
      data: {}
    });
  }
}

/**
 * 用户登录控制器
 * 处理用户登录请求
 * @param {Object} request - Fastify请求对象，包含用户名和密码
 * @param {Object} reply - Fastify响应对象
 * @returns {Object} 登录结果响应，包含认证令牌
 */
async function login(request, reply) {
  try {
    const { username, password } = request.body;
    const result = await authService.loginUser(username, password);
    return reply.send({
      code: 1,
      success: true,
      message: '登录成功',
      data: result
    });
  } catch (error) {
    return reply.code(401).send({
      code: 401,
      success: false,
      message: error.message,
      data: {}
    });
  }
}

export default { register, login };